import router from "./router"
import useUser from "./stores/user"
import useRoutes from "@/stores/routes"
import NProgress from 'nprogress'
import "nprogress/nprogress.css"
import {ElMessage} from "element-plus"

NProgress.configure({showSpinner: false})

const getToken = () => {
    let token: string | null = localStorage.getItem("token")
    if (token) {
        return token;
    } else {
        return '';
    }
};

// 白名单
const whiteList: string[] = ['/login', '/register']

// 路由前置守卫
router.beforeEach((to, from, next) => {
    const userStore = useUser();
    const routesStore = useRoutes();
    NProgress.start();// 开启进度条
    if (getToken()) {
        /* has token*/
        if (to.path === '/login') {
            next({path: '/'});
            NProgress.done();// 完成进度条
        } else {
            if (userStore.roles.length === 0) {
                //判断当前用户是否获取到用户信息
                userStore.GetUserInfo().then(() => {
                    // 根据roles权限生成可访问的路由表
                    routesStore.GenerateRoutes().then((accessRoutes: any) => {
                        console.log("添加路由前：", accessRoutes)
                        // 动态添加可访问路由表
                        accessRoutes.forEach((route: any) => {
                            router.addRoute(route);
                        })
                        next({...to, replace: true});// hack方法 确保addRoutes已完成
                        console.log("路由信息：", router.getRoutes())
                    })
                }).catch((err) => {
                    userStore.Logout().then(() => {
                        ElMessage.error(err);
                        next({path: '/'});
                    })
                })
            } else {
                next();
            }
        }
    } else {
        // 没有token
        // 检查是否在白名单中
        if (whiteList.indexOf(to.path) > -1) {
            // 在免登录白名单，直接进入
            next();
        } else {
            next(`/login?redirect=${to.fullPath}`); // 否则全部重定向到登录页
            NProgress.done();
        }
    }
})

// 路由后置守卫
router.afterEach(() => {
    NProgress.done()
})